import {authCard} from "../../api/card";
import {getCard, setCard} from "../../utils/auth";

const state = {
  cardNo: null,
  password: null,
  status: null,
  balance: null,
  auth: getCard(),
}

const mutations = {
  set_cardNo: (state, cardNo) => {
    state.cardNo = cardNo;
  },
  set_password: (state, password) => {
    state.password = password;
  },
  set_status: (state, status) => {
    state.status = status;
  },
  set_balance: (state, balance) => {
    state.balance = balance;
  },
  set_auth: state => {
    state.auth = state.cardNo + ':' + state.password;
    setCard(state.auth);
  }
}

const actions = {
  resume({state, dispatch}) {
    return new Promise(async (resolve, reject) => {
      if (state.auth) {
        const args = state.auth.split(":");
        if (args.length !== 2) reject('Invalid credential');
        const ret = await dispatch('authenticate', {
          cardNo: args[0],
          password: args[1]
        }).catch(err => reject(err));
        if (ret) resolve(ret);
        else reject('No response');
      }
      else resolve(null);
    })
  },
  authenticate({commit}, cardInfo) {
    return new Promise((resolve, reject) => {
      const {cardNo, password} = cardInfo;
      if (!cardNo || !password) reject('Invalid credential');
      authCard(cardNo, password).subscribe(res => {
        if (res.data) {
          commit('set_cardNo', res.data.cardNo);
          commit('set_password', res.data.password);
          commit('set_status', res.data.status);
          commit('set_balance', res.data.balance);
          commit('set_auth');
          resolve(res.data);
        }
        else reject('Credential not found')
      }, err => reject(err));
    })
  },
  logout({commit}) {
    commit('set_cardNo', null);
    commit('set_password', null);
    commit('set_status', null);
    commit('set_balance', null);
    commit('set_auth', null);
  }
}

export default {
  namespaced: true,
  state, mutations, actions
}
